const User = require("../model/user/user")
const { need_token } = require("./needToken")
const {
    checkAll
} = require("./findModel")

const check = (rule) => {
    try {
        return async function (ctx, next) {
            let token = await need_token(ctx.headers.authorization)
            console.log(token);
            if (token.code == 200) {
                let res = await checkAll(rule, token.username)
                if (res) {
                    await next()
                } else {
                    // 如果用户编辑自己的资料 则通过
                    if (rule === "edituser") {
                        const { id } = ctx.params
                        let name = await User.findOne({ attributes: ["username"], where: { id } })
                        if (token.username == name.username) {
                            await next()
                        } else {
                            ctx.body = {
                                msg: "操作失败 无权限",
                                code: "400",
                            }
                        }
                    } else {
                        ctx.body = {
                            msg: "操作失败a 无权限",
                            code: "400",
                        }
                    }
                }
            } else {
                ctx.body = {
                    msg: "token验证失败",
                    code: "400"
                }
            }
        }
    } catch (err) {
        ctx.body = {
            msg: "操作失败",
            code: "400",
            error: err
        }
    }
}


module.exports = { check }